import { isObject } from '@/utils';
import { useRef, useState } from 'react';
import { useCall, useRefState, useSetter, useSimpleMemo } from '.';

function usePaginationCommon() {
  const tableRef = useRef();
  const refresh = useCall(() => tableRef.current?.refresh?.());

  const selectedRef = useRef([]);
  const onSelect = useSetter(selectedRef, ['current']);
  const reset = useCall(() => {
    onSelect([]);
    refresh();
  });

  const [searchData, setSearchData] = useState([{ _: Date.now() }]);
  const emptyStrToNull = (obj) => {
    for (let key in obj) {
      let val = obj[key];
      if (val === '') obj[key] = null;
      if (isObject(val)) emptyStrToNull(val);
    }
  };
  const onSearch = useCall((formData) => {
    let next = Date.now();
    if (next - searchData[0]._ < 500) next = searchData[0]._;
    emptyStrToNull(formData);
    setSearchData([
      {
        ...formData,
        _: next,
      },
    ]);
  });

  const ref = useRef();
  const hasSelected = useRefState(selectedRef, (v) => v?.length > 0);
  ref.current = useSimpleMemo({
    ref,
    tableRef,
    searchData,
    onSearch,
    onSelect,
    selectedRef,
    hasSelected,
    refresh,
    reset,
  });
  return ref.current;
}

export default usePaginationCommon;
